package org.csu.onlineedubackend.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.csu.onlineedubackend.dto.StudentCourseDTO;
import org.csu.onlineedubackend.entity.Course;
import org.csu.onlineedubackend.entity.User;
import org.csu.onlineedubackend.mapper.CourseMapper;
import org.csu.onlineedubackend.result.CommonResponse;
import org.csu.onlineedubackend.service.LogService;
import org.csu.onlineedubackend.service.StudentCourseService;
import org.csu.onlineedubackend.result.ResponseCode;
import org.csu.onlineedubackend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.HashMap;

import org.csu.onlineedubackend.result.ResponseCode;


@RestController
@RequestMapping("/api/studentcourse")
@Slf4j
public class StudentCourseController {
    // ... 课程相关接口

    @Autowired
    private StudentCourseService studentCourseService;
    
    @Autowired
    private CourseMapper courseMapper;

    @Autowired
    private LogService logService;

    @Autowired
    private UserService userService;

    // 获取学生课程列表（Dashboard）
    @GetMapping("{id}/courses")
    public CommonResponse<List<StudentCourseDTO>> getStudentCourses(@PathVariable("id") Integer studentId) {
        log.info("获取学生课程列表 - 学生ID: {}", studentId);
        List<StudentCourseDTO> courses = studentCourseService.getStudentCourses(studentId);
        log.info("获取学生课程列表成功 - 学生ID: {}, 课程数: {}", studentId, courses.size());
        return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "获取成功", courses);
    }

    // 更新课程学习进度
    @PutMapping("{studentId}/courses/{courseId}/progress")
    public CommonResponse<Boolean> updateCourseProgress(
            @PathVariable Integer studentId,
            @PathVariable Integer courseId,
            @RequestParam Float progress,
            HttpServletRequest request) {
        log.info("更新课程学习进度 - 学生ID: {}, 课程ID: {}, 进度: {}", studentId, courseId, progress);
        boolean success = studentCourseService.updateCourseProgress(studentId, courseId, progress);
        if (success) {
            log.info("更新课程学习进度成功 - 学生ID: {}, 课程ID: {}", studentId, courseId);
            // 日志记录
            User user = userService.getById(studentId);
            String username = user != null ? user.getUsername() : null;
            String ip = request.getRemoteAddr();
            String userAgent = request.getHeader("User-Agent");
            Course course = courseMapper.selectById(courseId);
            String courseTitle = course != null ? course.getTitle() : null;
            logService.recordCourseProgress(studentId, username, courseId, courseTitle, progress, ip, userAgent);
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "更新成功", true);
        } else {
            log.warn("更新课程学习进度失败 - 学生ID: {}, 课程ID: {}", studentId, courseId);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "更新失败");
        }
    }

    /**
     * 学生订阅课程
     * @param id 课程ID
     * @param studentId 学生ID
     * @param level 课程级别
     * @param isFree 是否免费
     * @return 订阅结果
     */
    @PostMapping("{id}/subscribe")
    public CommonResponse<?> subscribe(
            @PathVariable Integer id,
            @RequestParam Integer studentId,
            HttpServletRequest request,
            @RequestParam(required = false, defaultValue = "基础") String level,
            @RequestParam(required = false, defaultValue = "false") Boolean isFree
            ) {
        
        log.info("学生订阅课程 - 课程ID: {}, 学生ID: {}, 级别: {}, 是否免费: {}", id, studentId, level, isFree);
        
        try {
            // 验证参数
            if (id == null || studentId == null) {
                log.warn("订阅课程参数错误 - 课程ID: {}, 学生ID: {}", id, studentId);
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "参数错误", false);
            }
            
            // 检查课程是否存在
            Course course = courseMapper.selectById(id);
            if (course == null) {
                log.warn("订阅课程失败 - 课程不存在, 课程ID: {}", id);
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "课程不存在", false);
            }
            
            // 检查是否已订阅
            try {
                int subscribed = courseMapper.checkCourseSubscription(studentId, id);
                if (subscribed > 0) {
                    log.info("学生已订阅该课程 - 学生ID: {}, 课程ID: {}", studentId, id);
                    return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "已订阅", true);
                }
            } catch (Exception e) {
                log.warn("检查订阅状态失败，继续执行订阅操作 - 学生ID: {}, 课程ID: {}", studentId, id);
            }
            
            boolean ok = studentCourseService.subscribe(studentId, id, level, isFree);
            if (ok) {
                log.info("订阅课程成功 - 课程ID: {}, 学生ID: {}", id, studentId);
                
                // 更新课程订阅人数
                try {
                    Course updatedCourse = courseMapper.selectById(id);
                    if (updatedCourse != null && (updatedCourse.getSubscriberCount() == null || updatedCourse.getSubscriberCount() == 0)) {
                        // 如果订阅人数为0，重新计算并更新
                        int subscriberCount = courseMapper.countCourseSubscriptions(id);
                        updatedCourse.setSubscriberCount(subscriberCount);
                        courseMapper.updateById(updatedCourse);
                        log.info("更新课程订阅人数 - 课程ID: {}, 订阅人数: {}", id, subscriberCount);
                    }
                } catch (Exception e) {
                    log.error("更新课程订阅人数失败 - 课程ID: {}", id, e);
                }
                // 日志记录
                User user = userService.getById(studentId);
                String username = user != null ? user.getUsername() : null;
                String ip = request.getRemoteAddr();
                String userAgent = request.getHeader("User-Agent");
                String courseTitle = course.getTitle();
                logService.recordCourseSubscribe(studentId, username, id, courseTitle, ip, userAgent, true);
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "订阅成功", true);
            } else {
                log.warn("订阅课程失败 - 课程ID: {}, 学生ID: {}", id, studentId);
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "订阅失败", false);
            }
        } catch (Exception e) {
            log.error("订阅课程异常 - 课程ID: {}, 学生ID: {}, 错误: {}", id, studentId, e.getMessage(), e);
            e.printStackTrace(); // 打印详细错误堆栈
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "订阅异常，请稍后重试", false);
        }
    }
    
    // // 取消订阅课程
    @DeleteMapping("/{id}/unsubscribe")
    public CommonResponse<?> unsubscribe(
            @PathVariable Integer id,
            @RequestParam Integer studentId,
            HttpServletRequest request) {
        log.info("取消订阅课程 - 课程ID: {}, 学生ID: {}", id, studentId);
        
        try {
            // 验证参数
            if (id == null || studentId == null) {
                log.warn("取消订阅课程参数错误 - 课程ID: {}, 学生ID: {}", id, studentId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "参数错误");
            }
            
            // 检查课程是否存在
            Course course = courseMapper.selectById(id);
            if (course == null) {
                log.warn("取消订阅课程失败 - 课程不存在, 课程ID: {}", id);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "课程不存在");
            }
            
            try {
                // 检查是否已订阅
                if (!studentCourseService.isSubscribed(studentId, id)) {
                    log.warn("取消订阅课程失败 - 未订阅课程, 课程ID: {}, 学生ID: {}", id, studentId);
                    return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "未订阅该课程");
                }
            } catch (Exception e) {
                // 如果检查订阅状态时出错，打印错误并继续尝试取消订阅
                log.warn("检查订阅状态异常 - 课程ID: {}, 学生ID: {}, 错误: {}", id, studentId, e.getMessage());
                System.out.println("检查订阅状态异常详细信息：");
                e.printStackTrace();
                // 继续执行，尝试取消订阅
            }
            
            boolean ok = studentCourseService.unsubscribe(studentId, id);
            if (ok) {
                log.info("取消订阅课程成功 - 课程ID: {}, 学生ID: {}", id, studentId);
                // 日志记录
                User user = userService.getById(studentId);
                String username = user != null ? user.getUsername() : null;
                String ip = request.getRemoteAddr();
                String userAgent = request.getHeader("User-Agent");
                String courseTitle = course.getTitle();
                logService.recordCourseSubscribe(studentId, username, id, courseTitle, ip, userAgent, false);
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "取消订阅成功", true);
            } else {
                log.warn("取消订阅课程失败 - 课程ID: {}, 学生ID: {}", id, studentId);
                return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "取消订阅失败");
            }
        } catch (Exception e) {
            log.error("取消订阅课程异常 - 课程ID: {}, 学生ID: {}, 错误: {}", id, studentId, e.getMessage(), e);
            // 打印详细错误堆栈，便于排查问题
            System.out.println("取消订阅课程异常详细信息：");
            e.printStackTrace();
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "取消订阅失败: " + e.getMessage());
        }
    }

    // // 查询是否已订阅
    @GetMapping("{id}/isSubscribe/{studentId}")
    public CommonResponse<Boolean> isSubscribed(@PathVariable Integer id, @PathVariable Integer studentId) {
        log.info("查询是否已订阅 - 课程ID: {}, 学生ID: {}", id, studentId);
        
        try {
            // 检查课程是否存在
            Course course = courseMapper.selectById(id);
            if (course == null) {
                log.warn("查询是否已订阅失败 - 课程不存在, 课程ID: {}", id);
                // 返回未订阅状态而不是错误，避免前端出现500错误
                return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "课程不存在，视为未订阅", false);
            }
            
            boolean ok = studentCourseService.isSubscribed(studentId, id);
            log.info("查询是否已订阅结果 - 课程ID: {}, 学生ID: {}, 是否已订阅: {}", id, studentId, ok);
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "查询成功", ok);
        } catch (Exception e) {
            log.error("查询是否已订阅异常 - 课程ID: {}, 学生ID: {}, 错误: {}", id, studentId, e.getMessage(), e);
            e.printStackTrace(); // 打印详细错误堆栈
            // 返回未订阅状态而不是错误，避免前端出现500错误
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "查询异常，视为未订阅", false);
        }
    }

    // 获取所有课程
    @GetMapping("/all")
    public CommonResponse<List<Course>> getAllCourses() {
        try {
            List<Course> courses = courseMapper.selectList(null);
            log.info("获取所有课程成功，共{}门课程", courses.size());
            return CommonResponse.createForSuccess(ResponseCode.SUCCESS.getCode(), "获取所有课程成功", courses);
        } catch (Exception e) {
            log.error("获取课程失败: {}", e.getMessage(), e);
            return CommonResponse.createForError(ResponseCode.ERROR.getCode(), "获取课程失败: " + e.getMessage());
        }
    }

    @GetMapping("/pending-assignments")
    public CommonResponse getPendingAssignments(@RequestParam("userId") Long userId) {
        List<Map<String, Object>> pendingAssignments = studentCourseService.getPendingAssignments(userId);
        return CommonResponse.success(pendingAssignments);
    }
}